package cn.lhn.ridersclub.service;

import cn.lhn.ridersclub.entity.Captcha;
import cn.lhn.ridersclub.mapper.CaptchaMapper;
import cn.lhn.ridersclub.util.EmailSender;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Random;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    private String content = "亲爱的用户：\n" +
            "    您好！\n" +
            "    欢迎您使用Riders Club车友互助平台，您正在进行（do this）的操作，以下是您的验证码：\n" +
            "    code\n" +
            "    验证码五分钟内有效，请勿与任何人分享您的验证码！\n" +
            "\n" +
            "\n" +
            "                                ————Riders Club开发者";

    private final CaptchaMapper captchaMapper;

    private final EmailSender emailSender;

    public CaptchaServiceImpl(CaptchaMapper captchaMapper, EmailSender emailSender) {
        this.captchaMapper = captchaMapper;
        this.emailSender = emailSender;
    }

    @Override
    public void sendCaptchaMail(String email, String purposes) throws RuntimeException {

        //  随机生成6位数验证码
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(new Random().nextInt(9));
        }

        //  编辑邮件内容
        String message = content.replace("do this", purposes).replace("code", sb);

        //  发送邮件
        emailSender.sendSimpleMail(email, "验证码", message);

        //  插入记录
        Captcha captcha = getCaptchaByEmail(email);
        if (captcha == null) {
            captcha = new Captcha(null, email, sb.toString(), true, LocalDateTime.now());

            //  插入记录
            captchaMapper.insert(captcha);
        }
        else {
            //  设置新的数据
            captcha.setCode(sb.toString());;
            captcha.setAvailable(true);
            captcha.setCreateTime(LocalDateTime.now());

            //  更新记录
            captchaMapper.updateById(captcha);
        }
    }

    @Override
    public void verifyCaptcha(String email, String code) throws RuntimeException {

        //  查询记录
        Captcha captcha = getCaptchaByEmail(email);
        if (captcha == null) {
            throw new RuntimeException("验证码验证失败");
        }

        //  验证码是否可用
        if (!captcha.isAvailable()) {
            throw new RuntimeException("验证码已失效");
        }

        //  验证码是否匹配
        if (!captcha.getCode().equals(code)) {
            throw new RuntimeException("验证码不正确");
        }

        //  验证码是否超时
        LocalDateTime create = captcha.getCreateTime();
        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.between(create, now);
        if (duration.toMinutes() > 5) {
            throw new RuntimeException("验证码超时");
        }

        //  验证通过，将此验证码置为不可用
        captcha.setAvailable(false);
        captchaMapper.updateById(captcha);
    }

    @Override
    public Captcha getCaptchaByEmail(String email) {

        QueryWrapper<Captcha> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        return captchaMapper.selectOne(wrapper);
    }
}
